// pages/imgCreation/index.js
import utf8Array2Str from 'utf8array2str';

const {
  aiCreationApi
} = require('../../../api/index')
const {
  GPTSHIXIANJIA
} = require('../../../api/config/config')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    logo: "/assets/img/logo_40_40@2.png",
    imgListLength: 0,
    creationImgRes: null, //结果
    requestTask: null,
    // sendData: null,
    timer: null,
    createtitle: '',
    spacetype: '',
    header:{
      Authorization: wx.getStorageSync('token'),
      Accept:'text/event-stream'
    },
    lastId: '' //最后一次通知的id
  },
  // 页面跳转
  toPage() {
    wx.navigateTo({
      url: '/pages/ai/creationComplete/index',
    })
  },
  //生命周期函数--监听页面加载
  onLoad(options) {
    if (options) {
      this.setData({
        createtitle: options.createtitle,
        spacetype: options.spacetype
      })
    }
    this.setData({
      imgListLength: wx.getStorageSync('drawingParameter').num
    })
    this.initSSE() //连接SSE
    // this.createImg() //创建生图任务
    // setTimeout(() => {
    //   this.createImg()
    // }, 1000)
    wx.onNetworkStatusChange(this.networkHandler)
  },
  // 建立SSE连接
  initSSE() {
    let _this = this
    console.log('token', wx.getStorageSync('token'));
    this.data.requestTask = wx.request({
      // url: `${GPTSHIXIANJIA}/api/app/create-image/q-image`, // 需要请求的接口地址
      url: `${GPTSHIXIANJIA}/sse-notifications`,
      header:_this.data.header,
      enableChunked: true, // enableChunked必须为true
      // data: {
      //   Id: wx.getStorageSync('userInfo').UserId,
      //   MsgId: wx.getStorageSync('drawingParameter').msgId,
      //   t: wx.getStorageSync('token').split(' ')[1],
      //   ct: 5
      // },
      success: (res) => {
        console.log('连接成功');
      },
      fail: (res) => {
        console.log('连接失败');
        // wx.showToast({
        //   title: '连接失败',
        //   icon: 'none',
        // })
        _this.initSSE() //连接失败重连
      }
    })
    // SSE监听
    this.data.requestTask.onChunkReceived(this.serverResponse)
  },
  // 创建生图任务
  createImg() {
    if (wx.getStorageSync('drawingParameter')) {
      aiCreationApi.creatingImg(wx.getStorageSync('drawingParameter')).then(res => {
        console.log('创建生图任务', res);
        if (res.statusCode === 400) {
          wx.showToast({
            title: '灵感值不足，探索草图里网页端、App，或完成任务获得更多灵感值',
            icon: "none",
            duration: 5000
          })
          this.data.requestTask.offChunkReceived(this.serverResponse)
        }
      }).catch(err => {
        console.log('生图失败', err);
      })
    }
  },
  // 生图状态追踪
  serverResponse(res) {
    // arrayBuffer转string
    let jsonString = utf8Array2Str(new Uint8Array(res.data));
    console.log('jsonString', jsonString);
    // 事件名为createminiimage
    if (jsonString.split('jsonString:')[0].split('event:')[1].split('data')[0].trim() === 'createminiimage') {
      // console.log(jsonString.split('jsonString:')[0].split('event:')[1].split('data')[0]); //event名称
      if (jsonString.includes("data")) {
        this.data.header['last-Event-Id'] = jsonString.split('jsonString:')[0].split('id:')[1].split('event')[0]
        this.data.creationImgRes = JSON.parse(jsonString.split("data:")[1])
        // console.log('重连header', this.data.header);
        console.log('生图状态', this.data.creationImgRes);
        // 生图成功
        if (this.data.creationImgRes.StatusCode === 200) {
          wx.onNetworkStatusChange(this.networkHandler) //关闭网络监听
          wx.setStorageSync('shareImgList', {
            keywords: wx.getStorageSync('drawingParameter')?.forwardDescribe, //可选
            imgList: this.data.creationImgRes.Result.map(item => item.picture_str),
            ratio: wx.getStorageSync('drawingParameter')?.size,
            style: wx.getStorageSync('styleStr')
          })
          wx.redirectTo({
            url: `/pages/ai/creationComplete/index?type=1&createtitle=${this.data.createtitle}&spacetype=${this.data.spacetype}`,
          })
        }
        // if (this.data.creationImgRes.StatusCode === 2001) {
        //   wx.showToast({
        //     title: "生图中,请等待",
        //     duration: 1000,
        //   })
        // }
        if (this.data.creationImgRes.StatusCode === 5002) {
          wx.showToast({
            title: "生图失败,请重试",
            duration: 2000,
            icon: "error"
          })
        }
      }
    }
    // if (jsonString.includes("data")) {
    //   this.data.creationImgRes = JSON.parse(jsonString.split("data:")[1])
    //   console.log('生图状态', this.data.creationImgRes);
    //   // 生图成功
    //   if (this.data.creationImgRes.StatusCode === 200) {
    //     // wx.onNetworkStatusChange(this.networkHandler) //关闭网络监听
    //     wx.setStorageSync('shareImgList', {
    //       keywords: wx.getStorageSync('drawingParameter')?.forwardDescribe, //可选
    //       imgList: this.data.creationImgRes.Result.map(item => item.picture_str),
    //       ratio: wx.getStorageSync('drawingParameter')?.size,
    //       style: wx.getStorageSync('styleStr')
    //     })
    //     wx.redirectTo({
    //       url: `/pages/ai/creationComplete/index?type=1&createtitle=${this.data.createtitle}&spacetype=${this.data.spacetype}`,
    //     })
    //   }
    //   // if (this.data.creationImgRes.StatusCode === 2001) {
    //   //   wx.showToast({
    //   //     title: "生图中,请等待",
    //   //     duration: 1000,
    //   //   })
    //   // }
    //   if (this.data.creationImgRes.StatusCode === 5002) {
    //     wx.showToast({
    //       title: "生图失败,请重试",
    //       duration: 2000,
    //       icon: "error"
    //     })
    //   }
    // }
  },
  // 网络状态监听
  networkHandler(res) {
    console.log('网络', res)
    let msg = ''
    if (!res.isConnected) { // 无网络
      msg = '当前网络不可用，请检查你的网络设置'
      // _this.data.requestTask.offChunkReceived(this.serverResponse)
    } else if (res.networkType === 'none') {
      msg = '网络开小差了,请网络良好后重试'
      // _this.data.requestTask.offChunkReceived(this.serverResponse)
    }
    // 有网络
    if (res.isConnected) {
      // _this.initSSE()
      // _this.createImg()
    }
    if (msg) {
      wx.showToast({
        title: msg,
        icon: 'none',
      })
      return false
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.data.requestTask.offChunkReceived(this.serverResponse)
    wx.onNetworkStatusChange(this.networkHandler) //关闭网络监听
    // console.log('页面销毁');
  }
})